package org.springframework.beans.factory.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * BeanDefinitionDocumentReader类的默认实现
 * 根据"spring-beans"的dtd或schema格式读取bean定义
 * xml文档所必须的元素, 结构, 属性很难再类中编码
 * 类解析所有bean定义元素，而不是beans根元素
 * @author lxz
 *
 */
public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {

    private static final String BEAN_ELEMENT = BeanDefinitionParserDelegate.BEAN_ELEMENT;
    
    @Override
    public void registerBeanDefinitions(Document doc,
            XmlReaderContext readerContext) {
        Element root = doc.getDocumentElement();
        BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);
        preProcessXml(root);
        parseBeanDefinitions(root, delegate);
        postProcessXml(root);
        
    }
    
    private void postProcessXml(Element root) {
        
    }

    private void parseBeanDefinitions(Element root,
            BeanDefinitionParserDelegate delegate) {
        if (delegate.isDefaultNamespace(delegate.getNamespaceURI(root))) {
            NodeList nodeList  = root.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node instanceof Element) {
                    Element ele = (Element) node;
                    String namespaceUri = delegate.getNamespaceURI(ele);
                    if (delegate.isDefaultNamespace(namespaceUri)) {
                        parseDefaultElement(ele, delegate);
                    } else {
                        
                    }
                }
            }
        }
    }

    private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
        if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
            processBeanDefinition(ele, delegate);
        }
    }

    private void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
        
    }
    
    private void preProcessXml(Element root) {
        
    }

    private BeanDefinitionParserDelegate createHelper(XmlReaderContext readerContext, Element root) {
        BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
        delegate.initDefaults(root);
        return delegate;
    }

}
